﻿using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace MyHttp.http
{
    public class Response
    {
        public enum STATUS_CODE { STATUS_SUCCESS=200, STATUS_REDIRECT, STATUS_MOVED, STATUS_NOT_FOUND=404 };

        private HttpListenerResponse rawResponse;
        private Stream outputStream;

        public Response(HttpListenerResponse response)
        {
            this.rawResponse = response;
            this.outputStream = response.OutputStream;
        }

        public bool HasOutput
        {
            get
            {
                return !outputStream.CanWrite;
            }
        }

        public bool outputJson(STATUS_CODE statusCode, Object content)
        {
            if (this.HasOutput)
            {
                //TODO: throw an exception
                return false;
            }
            String json = JsonConvert.SerializeObject(content);
            // TODO: get encoding
            byte[] buffer = Encoding.Default.GetBytes(json);
            // TODO: asyncCallback
            this.outputStream.BeginWrite(buffer, 0, buffer.Length, null, null);
            return true;
        }
    }
}
